// pages/createThemeOverride/createThemeOverride.js
let http = require('../../utils/api.js');
let domain = require('../../utils/api.js');
import {
    myHttps
} from '../../utils/util.js';
import {
    myHttpss
} from '../../utils/json.js';
Page({
    data: {
        hiddenLoading: false,
        show: false, //弹框 二维码
        title: '', //标题
        desc: '', //描述
        source: '', //来源接口获取得数据
        hiddenLoading: false,
        litems: [{
            status: 1,
            id: 0,
            'value': '全部'
        }, {
            status: 0,
            id: 1,
            'value': '标题匹配'
        }, {
            status: 0,
            id: 2,
            'value': '全文匹配'
        }, ], //筛选的匹配 
        jes: '',
        jess: '', //匹配 全部all 标题title 全文fullText
        tihuoWay: '必包含此关键词',
        wgList: [{
            indexs: '0',
            type: 'Must',
            tname: '必包含此关键词',
            content: '',
            select: false,
            ok: false
        }],
        pop: {
            indexs: '1',
            type: 'Must',
            tname: '必包含此关键词',
            content: '',
            select: false,
            ok: false
        },
        xiala: [{
                name: '必包含此关键词',
                type: 'Must'
            },
            {
                name: '可包含此关键词',
                type: 'Should'
            },
            {
                name: '不包含此关键词',
                type: 'MustNot'
            }
        ],
        checkedList: [], //确认资源  公众号选中得资源
        key: false, //控制关键词的显示与隐藏
        userId: '', //用户id
        role: '', //是否是作者身份
        domain: '', //ip
        avatar: '', //图片路径
        media: '',
        goMediaList:'',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            domain: domain.domain
        })
        var that = this;
        that.setData({
            userId: wx.getStorageSync('userId')
        })
        that.users(), //获取用户详情
            that.creatThemefrom() //调用获取来源
        wx.getStorage({
            key: 'wgList',
            success: function(res) {
                that.setData({
                    wgList: res.data
                });
            }
        });
        wx.getStorage({ //微信公众号得缓存
            key: 'apply',
            success: function(res) {
                that.setData({
                    checkedList: res.data
                });
            }
        });
        wx.getStorage({ //专业媒体得缓存
            key: 'mediaData',
            success: function(res) {
                // console.log(res)
                if (res.data) {
                    for (var i = 0; i < res.data.length; i++) {
                        that.data.checkedList.push(res.data[i])
                    }
                }
                var uniques = [];
                var stringify = {};
                for (var i = 0; i < that.data.checkedList.length; i++) { //去重
                    var keys = Object.keys(that.data.checkedList[i]);
                    keys.sort(function(a, b) {
                        return (Number(a) - Number(b));
                    });
                    var str = '';
                    for (var j = 0; j < keys.length; j++) {
                        str += JSON.stringify(keys[j]);
                        str += JSON.stringify(that.data.checkedList[i][keys[j]]);
                    }
                    if (!stringify.hasOwnProperty(str)) {
                        uniques.push(that.data.checkedList[i]);
                        stringify[str] = true;
                    }
                }
                that.setData({
                    media: res.data,
                    checkedList: uniques
                });
                // console.log(that.data.checkedList)
                // console.log(that.data.media)
            }

        });
        wx.getStorage({
            key: 'title',
            success: function(res) {
                that.setData({
                    title: res.data.title, //标题
                    desc: res.data.desc, //描述
                    jess: res.data.jess, //匹配
                });
                if (res.data.jess == 'all') {
                    that.data.litems[0].status = 1
                    that.setData({
                        litems: that.data.litems,
                        key: false
                    })
                } else if (res.data.jess == 'title') {
                    that.data.litems[1].status = 1
                    that.setData({
                        litems: that.data.litems,
                        key: true
                    })

                } else if (res.data.jess == 'fullText') {
                    that.data.litems[2].status = 1
                    that.setData({
                        litems: that.data.litems,
                        key: true
                    })
                }
            }
        });
        wx.getStorage({
            key: 'avatar', //touxiang
            success: function(res) {
                that.setData({
                    avatar: res.data
                });
                // console.log(that.data.avatar)
            },
        })

        // console.log(this.data.jess)
    },
    onShow() {
        var that = this;
        wx.getStorage({
            key: 'wgList',
            success: function(res) {
                that.setData({
                    wgList: res.data
                });
            }
        });
        wx.getStorage({ //微信公众号得缓存
            key: 'apply',
            success: function(res) {
                that.setData({
                    checkedList: res.data
                });
            }
        });
        wx.getStorage({ //专业媒体得缓存
            key: 'mediaData',
            success: function(res) {
                // console.log(res)
                if (res.data) {
                    for (var i = 0; i < res.data.length; i++) {
                        that.data.checkedList.push(res.data[i])
                    }
                }
                var uniques = [];
                var stringify = {};
                for (var i = 0; i < that.data.checkedList.length; i++) { //去重
                    var keys = Object.keys(that.data.checkedList[i]);
                    keys.sort(function(a, b) {
                        return (Number(a) - Number(b));
                    });
                    var str = '';
                    for (var j = 0; j < keys.length; j++) {
                        str += JSON.stringify(keys[j]);
                        str += JSON.stringify(that.data.checkedList[i][keys[j]]);
                    }
                    if (!stringify.hasOwnProperty(str)) {
                        uniques.push(that.data.checkedList[i]);
                        stringify[str] = true;
                    }
                }
                that.setData({
                    media: res.data,
                    checkedList: uniques
                });
                // console.log(that.data.checkedList)
                // console.log(that.data.media)
            }

        });
        wx.getStorage({
            key: 'title',
            success: function(res) {
                that.setData({
                    title: res.data.title, //标题
                    desc: res.data.desc, //描述
                    jess: res.data.jess, //匹配
                });
                if (res.data.jess == 'all') {
                    that.data.litems[0].status = 1
                    that.setData({
                        litems: that.data.litems,
                        key: false
                    })
                } else if (res.data.jess == 'title') {
                    that.data.litems[1].status = 1
                    that.setData({
                        litems: that.data.litems,
                        key: true
                    })

                } else if (res.data.jess == 'fullText') {
                    that.data.litems[2].status = 1
                    that.setData({
                        litems: that.data.litems,
                        key: true
                    })
                }
            }
        });
        wx.getStorage({
            key: 'avatar', //touxiang
            success: function(res) {
                that.setData({
                    avatar: res.data
                });
                // console.log(that.data.avatar)
            },
        })
    },
    // 获取来源得接口
    creatThemefrom() {
        let url = http.api.creatThemefrom;
        // console.log(url)
        myHttpss({
            url: url,
            method: "GET",
        }).then(res => {
            if (res.code == 1) {
                this.setData({
                    source: res.data.content,
                    hiddenLoading: true
                })
            }
        }).catch(err => {})
    },
    // 标题
    biaoti(e) {
        this.setData({
            title: e.detail.value
        });
    },
    // 描述
    miaoshu(e) {
        this.setData({
            desc: e.detail.value
        });
    },
    //获取详情接口
    users(id) {
        let url = http.api.userInfo + this.data.userId;
        myHttps({
            url: url,
            method: 'GET',
        }).then(res => {
            if (res.code == 1) {
                // console.log(res)
                this.setData({
                    role: res.data.role
                })
                if (res.data.role == "Subscriber") {
                    // console.log('Subscriber')
                    if (id == 1) {
                        this.setData({
                            show: true, //弹框 二维码
                            key: false, //控制关键词的显示与隐藏
                            jess: 'all', //筛选的值
                        })
                    } else if (id == 2) {
                        this.setData({
                            show: true, //弹框 二维码
                            key: false, //控制关键词的显示与隐藏
                            jess: 'all'
                        })
                    }
                } else if (res.data.role == "Author") {
                    // console.log('Author')
                    if (id == 1) {
                        this.setData({
                            key: true,
                            jess: 'title'
                        })
                    } else if (id == 2) {
                        this.setData({
                            key: true,
                            jess: 'fullText'
                        })
                    }
                }
            }
        })
    },
    //筛选点击单选
    chaclickss(e) {
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        if (id == 0) {
            this.setData({
                key: false,
                jess: 'all'
            })
        } else if (id == 1) {
            this.users(1)
            // this.setData({
            //     key: true,
            //     jess: 'title'
            // })
        } else if (id == 2) {
            this.users(2)
            // this.setData({
            //     key: true,
            //     jess: 'fullText'
            // })
        }
        // 判断是否是作者身份 是作者身份 筛选的三个选项都可以选
        console.log(this.data.role)
        if (this.data.role == 'Author') {
            for (var i = 0; i < this.data.litems.length; i++) {
                if (id == this.data.litems[i].id) {
                    this.data.litems[i].status = 1
                } else {
                    this.data.litems[i].status = 0
                }
            }
        } else if (this.data.role == 'Subscriber') {
            //不是作者身份 点标题匹配和全文匹配会出项进群的弹框 并且不能选择
            for (var i = 0; i < this.data.litems.length; i++) {
                this.data.litems[0].status = 1
            }
        }

        this.setData({
            litems: this.data.litems
        })
    },
    // 关闭弹框二维码
    closess() {
        this.setData({
            show: false, //弹框 二维码
        })
    },
    // 下拉菜单
    bindShowMsg(e) {
        //单独去控制某一个的显示隐藏
        // console.log(e)
        var index = e.currentTarget.dataset.index;
        this.data.wgList[index].select = !this.data.wgList[index].select;
        this.setData({
            wgList: this.data.wgList
        })
    },
    mySelect(e) {
        var index1 = e.currentTarget.dataset.index; //父集的索引
        var index2 = e.currentTarget.dataset.indexs; //当前的索引

        for (var i = 0; i < this.data.wgList.length; i++) {
            if (index1 == this.data.wgList[i].indexs) {
                this.data.wgList[i].tname = this.data.xiala[index2].name;
                this.data.wgList[i].type = this.data.xiala[index2].type;
                this.data.wgList[i].select = !this.data.wgList[i].select;
            }
        }
        this.setData({
            wgList: this.data.wgList
        })
    },
    getzi(e) {
        var val = e.detail.value;
        var index1 = e.currentTarget.dataset.index; //父集的索引
        for (var i = 0; i < this.data.wgList.length; i++) {
            if (index1 == this.data.wgList[i].indexs) {
                this.data.wgList[i].content = val
            }
        }
        this.setData({
            wgList: this.data.wgList
        })
        // console.log(this.data.wgList)
    },
    //点击加号
    addwz(e) {
        this.data.pop.indexs = parseInt(e.currentTarget.dataset.index) + 1;
        this.setData({
            pop: this.data.pop
        })
        for (var i = 0; i < this.data.wgList.length; i++) {
            if (e.currentTarget.dataset.index == this.data.wgList[i].indexs) {

                this.data.wgList[i].ok = true
            }
        }

        this.data.wgList.push(this.data.pop);
        this.setData({
            wgList: this.data.wgList
        })
        // console.log(this.data.wgList)
    },
    //删除某一项
    removewz(e) {
        var index = e.currentTarget.dataset.index;
        // console.log(index)
        this.data.wgList.splice(index, 1);
        // console.log(this.data.wgList)
        this.setData({
            wgList: this.data.wgList
        })
    },
    // 点击来源得每一项
    gosearch(e) {
        let id = e.currentTarget.dataset.id
        if (id == 1) {
            this.go_palic(id)
        } else if (id == 2) {
            this.goMedia()
        }
    },
    // 去往公众号页面
    go_palic(id) {
        var goMediaList = []
        if (this.data.checkedList) {
            for (var i = 0; i < this.data.checkedList.length; i++) {
                if (this.data.checkedList[i].platform_id >= 2) {
                    goMediaList.push(this.data.checkedList[i])
                }
            }
            this.setData({
                goMediaList: goMediaList
            })
            wx.setStorage({
                key: 'mediaData',
                data: this.data.goMediaList, //专业媒体
            })
        }
        var publicList = []
        for (var i = 0; i < this.data.checkedList.length; i++) {
            if (this.data.checkedList[i].platform_id == 1) {
                publicList.push(this.data.checkedList[i])
                wx.setStorage({
                    key: 'apply',
                    data: publicList, //公众号
                })
            }
        }
        wx.setStorage({
            key: 'wgList',
            data: this.data.wgList, //关键词
        })
        //标题描述匹配
        wx.setStorage({
            key: 'title',
            data: {
                title: this.data.title, //标题
                desc: this.data.desc, //描述
                jess: this.data.jess, //匹配
            }
        })
        wx.setStorage({
            key: 'avatar', //头像
            data: this.data.avatar
        })
        wx.navigateTo({
            url: "/pages/public/public?id=" + id
        })
    },
    // 去往媒体页面 
    goMedia() {
        wx.setStorage({
            key: 'wgList',
            data: this.data.wgList, //关键词
        })
        // wx.setStorage({
        //     key: 'apply',
        //     data: this.data.checkedList, //公众号
        // })
        // wx.setStorage({
        //     key: 'mediaData',
        //     data: this.data.media, //专业媒体
        // })
        var goMediaList = []
        if (this.data.checkedList){
            for (var i = 0; i < this.data.checkedList.length; i++) {
                if (this.data.checkedList[i].platform_id >= 2) {
                    goMediaList.push(this.data.checkedList[i])
                }
            }
            this.setData({
                goMediaList: goMediaList
            })
            wx.setStorage({
                key: 'mediaData',
                data: this.data.goMediaList, //专业媒体
            })
        }
        var publicList = []
        for (var i = 0; i < this.data.checkedList.length; i++) {
            if (this.data.checkedList[i].platform_id == 1) {
                publicList.push(this.data.checkedList[i])
                wx.setStorage({
                    key: 'apply',
                    data: publicList, //公众号
                })
            }
        }
        wx.setStorage({
            key: 'avatar', //头像
            data: this.data.avatar
        })
        //标题描述匹配
        wx.setStorage({
            key: 'title',
            data: {
                title: this.data.title, //标题
                desc: this.data.desc, //描述
                jess: this.data.jess, //匹配
            }
        })
        wx.navigateTo({
            url: '/pages/media/media',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    // 去往选择头像页面
    chooseAvatar() {
        wx.setStorage({
            key: 'wgList',
            data: this.data.wgList, //关键词
        })
        wx.setStorage({
            key: 'apply',
            data: this.data.checkedList, //公众号
        })
        // wx.setStorage({
        //     key: 'mediaData',
        //     data: this.data.media, //专业媒体
        // })
        //标题描述匹配
        wx.setStorage({
            key: 'title',
            data: {
                title: this.data.title, //标题
                desc: this.data.desc, //描述
                jess: this.data.jess, //匹配
            }
        })
        wx.redirectTo({
            url: '../themeAvatar/themeAvatar',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    //点击删除 资源
    close(e) {
        let index = e.currentTarget.dataset.index;
        let id = e.currentTarget.dataset.id;
        let obj = this.data.checkedList;
        //全部得删除
        obj.splice(index, 1)
        this.setData({
            checkedList: obj
        })
    },
    // 提交
    build() {
        let avatar; //头像
        if (this.data.avatar) {
            avatar = this.data.avatar
        } else {
            avatar = '/static/images/default.png'
        }
        // 判断title和content 来源 不为空
        if (this.data.checkedList == '' || this.data.checkedList == undefined) {
            wx.showToast({
                title: '来源不能为空',
                duration: 2000,
                icon: 'none',
            })
        } else if (this.data.title == '' || this.data.title == undefined) {
            wx.showToast({
                title: '标题不能为空',
                duration: 2000,
                icon: 'none',
            })
        } else if (this.data.desc == '' || this.data.desc == undefined) {
            wx.showToast({
                title: '描述不能为空',
                duration: 2000,
                icon: 'none',
            })
        } else {
            this.setData({
                hiddenLoading: false
            })
            for (var i = 0; i < this.data.wgList.length; i++) {
                delete this.data.wgList[i].indexs;
                delete this.data.wgList[i].tname;
                delete this.data.wgList[i].select;
                delete this.data.wgList[i].ok;
            }
            // console.log(this.data.wgList) //位置关键词
            // console.log(this.data.desc) //描述
            // console.log(this.data.title) //描述
            this.setData({
                show_build: true
            })
            let that = this;
            that.setData({
                show_build: true
            })
            // 判断如果jess不存在的话 就赋值all
            if (!this.data.jess) {
                this.setData({
                    jess: 'all'
                })
            }
            // 如果选择的是全文  就不传关键词
            if (this.data.jess == 'all') {
                var obj = {
                    'title': this.data.title,
                    'content': this.data.desc,
                    'match_type': this.data.jess,
                    'sources': this.data.checkedList,
                    'avatar': avatar,
                    'status': 'Pending' //新建
                }
            } else {
                var obj = {
                    'title': this.data.title,
                    'content': this.data.desc,
                    'match_type': this.data.jess,
                    'sources': this.data.checkedList,
                    'filters': this.data.wgList,
                    'avatar': avatar,
                    'status': 'Pending'
                }
            }
            // 立即创建接口
            let url = http.api.creatTheme;
            // console.log(url)
            myHttpss({
                url: url,
                method: "POST",
                data: obj
            }).then(res => {
                // console.log(res)
                if (res.code == 1) {
                    this.setData({
                        hiddenLoading: true
                    })
                    wx.showToast({
                        title: '创建成功',
                        icon: 'success',
                        duration: 2000,
                    })
                    setTimeout(function() {
                        // 创建成功后 清除页面公众号缓存数据
                        wx.removeStorage({
                            key: 'apply',
                            success: function(res) {},
                        })
                        wx.removeStorage({
                            key: 'title',
                            success: function(res) {},
                        })
                        wx.removeStorage({
                            key: 'mediaData',
                            success: function(res) {}, //专业媒体
                        })
                        wx.switchTab({
                            url: '../find/find'
                        });
                    }, 500)
                } else if (res.code == 401) {
                    this.setData({
                        hiddenLoading: true
                    })
                    wx.showToast({
                        title: '您还不是作者,不能选择标题匹配或全文匹配',
                        icon: 'none',
                        duration: 3000
                    })
                } else if (res.code == 0) {
                    // console.log(res.data)
                    this.setData({
                        hiddenLoading: true
                    })
                    wx.showToast({
                        title: res.data,
                        icon: 'none',
                        duration: 2000
                    })
                }
            }).catch(err => {})
        }
    },
    // 保存
    baocun() {
        let avatar; //头像
        if (this.data.avatar) {
            avatar = this.data.avatar
        } else {
            avatar = '/static/images/default.png'
        }
        // 判断title和content 来源 不为空
        if (this.data.checkedList == '' || this.data.checkedList == undefined) {
            wx.showToast({
                title: '来源不能为空',
                duration: 2000,
                icon: 'none',
            })
        } else if (this.data.title == '' || this.data.title == undefined) {
            wx.showToast({
                title: '标题不能为空',
                duration: 2000,
                icon: 'none',
            })
        } else if (this.data.desc == '' || this.data.desc == undefined) {
            wx.showToast({
                title: '描述不能为空',
                duration: 2000,
                icon: 'none',
            })
        } else {
            this.setData({
                hiddenLoading: false
            })
            for (var i = 0; i < this.data.wgList.length; i++) {
                delete this.data.wgList[i].indexs;
                delete this.data.wgList[i].tname;
                delete this.data.wgList[i].select;
                delete this.data.wgList[i].ok;
            }
            // console.log(this.data.wgList) //位置关键词
            // console.log(this.data.desc) //描述
            // console.log(this.data.title) //描述
            this.setData({
                show_build: true
            })
            let that = this;
            that.setData({
                show_build: true
            })
            // 判断如果jess不存在的话 就赋值all
            if (!this.data.jess) {
                this.setData({
                    jess: 'all'
                })
            }
            // 如果选择的是全文  就不传关键词
            if (this.data.jess == 'all') {
                var obj = {
                    'title': this.data.title,
                    'content': this.data.desc,
                    'match_type': this.data.jess,
                    'sources': this.data.checkedList,
                    'avatar': avatar,
                    'status': 'New' //保存
                }
            } else {
                var obj = {
                    'title': this.data.title,
                    'content': this.data.desc,
                    'match_type': this.data.jess,
                    'sources': this.data.checkedList,
                    'filters': this.data.wgList,
                    'avatar': avatar,
                    'status': 'New' //保存
                }
            }
            // 立即创建接口
            let url = http.api.creatTheme;
            // console.log(url)
            myHttpss({
                url: url,
                method: "POST",
                data: obj
            }).then(res => {
                // console.log(res)
                if (res.code == 1) {
                    this.setData({
                        hiddenLoading: true
                    })
                    wx.showToast({
                        title: '创建成功',
                        icon: 'success',
                        duration: 2000,
                    })
                    setTimeout(function() {
                        // 创建成功后 清除页面公众号缓存数据
                        wx.removeStorage({
                            key: 'apply',
                            success: function(res) {},
                        })
                        wx.removeStorage({
                            key: 'title',
                            success: function(res) {},
                        })
                        wx.removeStorage({
                            key: 'mediaData',
                            success: function(res) {}, //专业媒体
                        })
                        wx.switchTab({
                            url: '../find/find'
                        });
                    }, 500)
                } else if (res.code == 401) {
                    this.setData({
                        hiddenLoading: true
                    })
                    wx.showToast({
                        title: '您还不是作者,不能选择标题匹配或全文匹配',
                        icon: 'none',
                        duration: 3000
                    })
                } else if (res.code == 0) {
                    // console.log(res.data)
                    this.setData({
                        hiddenLoading: true
                    })
                    wx.showToast({
                        title: res.data,
                        icon: 'none',
                        duration: 2000
                    })
                }
            }).catch(err => {})
        }
    }
})